package com.kgcx.common.utils;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.GetObjectRequest;
import com.aliyun.oss.model.OSSObject;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.SimplifiedObjectMeta;
import com.kgcx.common.config.AliServerConfig;
import com.xiaoleilu.hutool.util.RandomUtil;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.entity.ContentType;

import java.io.IOException;
import java.io.InputStream;

/**
 * Created by Administrator on 2017/1/4.
 */
public class FileUtils {

    private static OSSClient ossClient;

    public static String ossImageBucket;

    public static String ossFileBucket;

    public static OSSClient getOssClient() {
        if (null == ossClient) {
            initClient();
        }
        return ossClient;
    }

    public static void initClient() {
        if (null == ossClient) {
            AliServerConfig aliServerConfig = ApplicationUtils.getBean(AliServerConfig.class);
            // endpoint以杭州为例，其它region请按实际情况填写
            // accessKey请登录https://ak-console.aliyun.com/#/查看
            // 创建OSSClient实例
            String endpoint = aliServerConfig.getOssEndpoint();
            ossClient = new OSSClient(endpoint, aliServerConfig.getAccessKeyId(),
                    aliServerConfig.getAccessKeySecret());
            ossImageBucket = aliServerConfig.getOssImageBucket();
            ossFileBucket = aliServerConfig.getOssFileBucket();
        }
    }

    public static void uploadFile(String bucketName, String key, InputStream inputStream,
                                  ObjectMetadata meta) {
        // 上传文件流
        getOssClient().putObject(bucketName, key, inputStream, meta);
        IOUtils.closeQuietly(inputStream);
    }

    public static void uploadFile(String bucketName, String key, InputStream inputStream) {
        // 上传文件流
        getOssClient().putObject(bucketName, key, inputStream);
        IOUtils.closeQuietly(inputStream);
    }

    public static void uploadFile(String key, InputStream inputStream) {
        // 上传文件流
        uploadFile(ossFileBucket, key, inputStream);
    }

    public static String uploadFile(InputStream inputStream) {
        String key = RandomUtil.randomUUID();
        // 上传文件流
        uploadFile(key, inputStream);
        return key;
    }


    public static InputStream getObject(String bucketName, String key) {
        OSSObject object = getOssClient().getObject(bucketName, key);
        return object.getObjectContent();
    }

    public static void deleteFile(String bucketName, String key) {
        getOssClient().deleteObject(bucketName, key);
    }


    public static InputStream getImage(String img) {
        return getObject(ossImageBucket, img);
    }

    /**
     * 获取图片的平均色值
     *
     * @param key
     * @return
     * @throws IOException
     */
    public static InputStream getImageAvgColor(String key) {
        String style = "image/average-hue";
        GetObjectRequest request = new GetObjectRequest(ossImageBucket, key);
        request.setProcess(style);
        OSSObject object = getOssClient().getObject(request);
        return object.getObjectContent();
    }

    public static Long getImageSize(String key) {
        SimplifiedObjectMeta objectMeta = getOssClient().getSimplifiedObjectMeta(
                ossImageBucket, key);
        return objectMeta.getSize();
    }


    public static void deleteImg(String key) {
        FileUtils.deleteFile(ossImageBucket, key);
    }


    public static String uploadImg(InputStream inputStream) {
        return uploadImg(inputStream, null);
    }

    public static String uploadImg(InputStream inputStream, String key) {

        if (StringUtils.isEmpty(key)) {
            key = RandomUtil.randomUUID();
        }
        // 创建上传Object的Metadata
        ObjectMetadata meta = new ObjectMetadata();

        meta.setContentType(ContentType.IMAGE_PNG.getMimeType());
        FileUtils.uploadFile(ossImageBucket, key, inputStream, meta);
        return key;
    }

    public static void main(String[] args) {
    }


  /*  public static Object getSTS() {
        // 只有 RAM用户（子账号）才能调用 AssumeRole 接口
        // 阿里云主账号的AccessKeys不能用于发起AssumeRole请求
        // 请首先在RAM控制台创建一个RAM用户，并为这个用户创建AccessKeys
        String accessKeyId = "LTAICVRvP16eo1kJ";
        String accessKeySecret = "tQ0NOzifMFbWFgOBFeJbcXqNYk0kZe";
        // AssumeRole API 请求参数: RoleArn, RoleSessionName, Policy, and DurationSeconds
        // RoleArn 需要在 RAM 控制台上获取
        String roleArn = "acs:ram::1411390257514788:role/ramupload";
        // RoleSessionName 是临时Token的会话名称，自己指定用于标识你的用户，主要用于审计，或者用于区分Token颁发给谁
        // 但是注意RoleSessionName的长度和规则，不要有空格，只能有'-' '_' 字母和数字等字符
        // 具体规则请参考API文档中的格式要求
        String roleSessionName = "alice-001";
        // 如何定制你的policy?
        String policy = "{\n" +
                "    \"Version\": \"1\", \n" +
                "    \"Statement\": [\n" +
                "        {\n" +
                "            \"Action\": [\n" +
                "                \"oss:GetBucket\", \n" +
                "                \"oss:GetObject\" \n" +
                "            ], \n" +
                "            \"Resource\": [\n" +
                "                \"acs:oss:*\"\n" +
                "            ], \n" +
                "            \"Effect\": \"Allow\"\n" +
                "        }\n" +
                "    ]\n" +
                "}";
        // 此处必须为 HTTPS
        ProtocolType protocolType = ProtocolType.HTTPS;
        try {
            final AssumeRoleResponse response = assumeRole(accessKeyId, accessKeySecret,
                    roleArn, roleSessionName, policy, protocolType);
            return response.getCredentials();
        } catch (ClientException e) {
            System.out.println("Failed to get a token.");
        }
        return null;
    }
    // 目前只有"cn-hangzhou"这个region可用, 不要使用填写其他region的值
    public static final String REGION_CN_HANGZHOU = "cn-hangzhou";
    // 当前 STS API 版本
    public static final String STS_API_VERSION = "2015-04-01";

    public static AssumeRoleResponse assumeRole(String accessKeyId, String accessKeySecret,
                                                String roleArn, String roleSessionName, String policy,
                                                ProtocolType protocolType) throws ClientException {
        try {
            // 创建一个 Aliyun Acs Client, 用于发起 OpenAPI 请求
            IClientProfile profile = DefaultProfile.getProfile(REGION_CN_HANGZHOU, accessKeyId, accessKeySecret);
            DefaultAcsClient client = new DefaultAcsClient(profile);
            // 创建一个 AssumeRoleRequest 并设置请求参数
            final AssumeRoleRequest request = new AssumeRoleRequest();
            request.setVersion(STS_API_VERSION);
            request.setMethod(MethodType.POST);
            request.setProtocol(protocolType);
            request.setRoleArn(roleArn);
            request.setRoleSessionName(roleSessionName);
            request.setPolicy(policy);
            // 发起请求，并得到response
            final AssumeRoleResponse response = client.getAcsResponse(request);
            return response;
        } catch (ClientException e) {
            throw e;
        } catch (ServerException e) {
            e.printStackTrace();
        } catch (com.aliyuncs.exceptions.ClientException e) {
            e.printStackTrace();
        }
        return null;
    }*/
}
